// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const KEY = "47cb7d22ce321d60ae38b98c0b56e17e"
var mqtt = require('../../utils/mqtt.min.js')
const crypto = require('../../utils/crypto');

Page({
  data: {
    motto: 'Hello World',
    title: '奈斯物联网小程序',
    weatherInfo: {},
    mqttAccountInfo: {
      productKey: "k130mtx8GH2",
      deviceName: "app_dev",
      deviceSecret: "5c49e8fd45f1ffac8ca7ca25da32801b",
    },
    sendData: {},
    sensorList: [{
        name: "温度",
        imageUrl: "/images/sensors/temp.png",
        value: 35,
        unit: "℃",
        top: 10,
        bottom: 40,
        isShow: true
      },
      {
        name: "湿度",
        imageUrl: "/images/sensors/humi.png",
        value: 40,
        unit: "%rh",
        top: 30,
        bottom: 20,
        isShow: true
      },
      {
        name: "光强",
        imageUrl: "/images/sensors/sun.png",
        value: 30,
        unit: "lx",
        top: 50,
        bottom: 60,
        isShow: true
      }, {
        name: "烟雾",
        imageUrl: "/images/sensors/smoke.png",
        value: 20,
        unit: "ppm",
        top: 70,
        bottom: 80,
        isShow: true
      }, {
        name: "灯",
        imageUrl: "/images/sensors/led.png",
        value: false,
        isShow: false
      }, {
        name: "风扇",
        imageUrl: "/images/sensors/fan.png",
        value: true,
        isShow: false
      }
    ]
  },
  onLoad() {
    this.getLocation()
    this.doConnect()

  },
  getLocation() {
    let that = this
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        console.log(res)
        const latitude = res.latitude
        const longitude = res.longitude
        const speed = res.speed
        const accuracy = res.accuracy

        wx.request({
          url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
          data: {
            key: KEY,
            location: longitude + "," + latitude
          },
          success(res) {
            console.log(res)
            let cityCode = res.data.regeocode.addressComponent.adcode
            wx.request({
              url: 'https://restapi.amap.com/v3/weather/weatherInfo?parameters',
              data: {
                key: KEY,
                city: cityCode
              },
              success(res) {
                console.log(res)
                let weather_info = res.data.lives[0]
                weather_info.imageUrl = "/images/weather/" + that.getIconKey(weather_info.weather) + ".png"
                console.log(weather_info)
                that.setData({
                  weatherInfo: weather_info
                })
              }
            })

          }
        })
      }
    })
  },
  getIconKey(weather) {
    const iconWeatherMap = {
      '风': ['有风', '平静', '微风', '和风', '清风', '强风/劲风', '疾风', '大风', '烈风', '风暴', '狂爆风', '飓风', '热带风暴', '龙卷风'],
      '多云': ['少云', '晴间多云', '多云'],
      '雪': ['雪', '阵雪', '小雪', '中雪', '大雪', '暴雪', '小雪-中雪', '中雪-大雪', '大雪-暴雪', '冷'],
      '雾': ['浮尘', '扬沙', '沙尘暴', '强沙尘暴', '雾', '浓雾', '强浓雾', '轻雾', '大雾', '特强浓雾'],
      '晴': ['晴', '热'],
      '雨夹雪': ['雨雪天气', '雨夹雪', '阵雨夹雪'],
      '雨': ['阵雨', '雷阵雨', '雷阵雨并伴有冰雹', '小雨', '中雨', '大雨', '暴雨', '大暴雨', '特大暴雨', '强阵雨', '强雷阵雨', '极端降雨', '毛毛雨/细雨', '雨', '小雨-中雨', '中雨-大雨', '大雨-暴雨', '暴雨-大暴雨', '大暴雨-特大暴雨', '冻雨'],
      '阴': ['阴', '霾', '中度霾', '重度霾', '严重霾', '未知']
    }
    // 这个是默认值
    let iconKey = '阴'
    for (const weatherKey in iconWeatherMap) {
      if (Object.hasOwnProperty.call(iconWeatherMap, weatherKey)) {
        const weatherNames = iconWeatherMap[weatherKey]
        const findWeatherItem = weatherNames.find(name => weather === name)
        if (findWeatherItem) {
          iconKey = weatherKey
          break
        }
      }
    }
    return iconKey
  },
  doConnect() {
    let that = this
    const options = this.initMqttOptions();
    this.data.client = mqtt.connect('wxs://' + this.data.mqttAccountInfo.productKey + '.iot-as-mqtt.cn-shanghai.aliyuncs.com', options)
    this.data.client.on('connect', function () {
      console.log('连接服务器成功')
      that.data.client.subscribe('/' + that.data.mqttAccountInfo.productKey + '/' + that.data.mqttAccountInfo.deviceName + '/user/get', function (err) {
        if (!err) {
          console.log('订阅成功！');
        }
      })
    })
    //接收消息监听
    that.data.client.on('message', function (topic, message) {
      let msg = message.toString();
      console.log('收到消息：' + msg);
      that.setData({
        sensorList: JSON.parse(message)
      })

    })
  },
  unconnect() {
    this.data.client.end();
    this.data.client = null;
    console.log("断开连接")
  },
  publish: function () {
    // 判断是否已成功连接
    if (!this.data.client || !this.data.client.connected) {
      console.log('发布失败');
      return;
    } else {
      const message = JSON.stringify(this.data.sendData);
      const topic_pub = "/" + this.data.mqttAccountInfo.productKey + "/" + this.data.mqttAccountInfo.deviceName + "/user/update"; //目的地址
      this.data.client.publish(topic_pub, message, error => {
        console.log(error || '消息发布成功');
      });
    }
  },
  //IoT平台mqtt连接参数初始化
  initMqttOptions() {
    const params = {
      productKey: this.data.mqttAccountInfo.productKey,
      deviceName: this.data.mqttAccountInfo.deviceName,
      deviceSecret: this.data.mqttAccountInfo.deviceSecret,
      timestamp: Date.now(),
    }
    //生成clientId，username，password
    const contentStr = "clientId" + params.clientId + "deviceName" + params.deviceName + "productKey" + params.productKey + "timestamp" + params.timestamp;
    const clientId = `${params.clientId}|securemode=2,signmethod=hmacsha1,timestamp=${params.timestamp}|`;
    const username = `${params.deviceName}&${params.productKey}`;
    const password = crypto.HmacSHA1(contentStr, params.deviceSecret).toString();
    const options = {
      wsOptions: {},
      protocolVersion: 4, //MQTT连接协议版本
      clientId: clientId,
      keepalive: 60,
      clean: false,
      username: username,
      password: password,
      reconnectPeriod: 1000, //1000毫秒，两次重新连接之间的间隔
      connectTimeout: 30 * 1000, //1000毫秒，两次重新连接之间的间隔
      resubscribe: true //如果连接断开并重新连接，则会再次自动订阅已订阅的主题（默认true）
    }
    return options;
  },
  buttonChange: function (e) {
    this.data.sensorList[e.currentTarget.dataset.param].value = !this.data.sensorList[e.currentTarget.dataset.param].value
    console.log(this.data.sensorList)
    this.data.sendData = this.data.sensorList
    this.publish()

  },



})